package com.dhy.scanercode;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dhy.R;
import com.dhy.utils.Config;
import com.dhy.utils.UDPBuild;
import com.dhy.utils.UDPSendReceive;
import com.dhy.zxing.android.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.os.Build.HOST;

public class MainActivity extends AppCompatActivity {

    private Button scan_btn;
    private UDPBuild udpBuild;
    private String scanresult;
    private AlertDialog.Builder builder;
    private TextView listText;
    private TextView phoneText;

    private PrintWriter printWriter;
    private BufferedReader in;
    private ExecutorService mExecutorService = null;
    private String receiveMsg;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                JSONObject objectData = (JSONObject) msg.obj;
                int port = 0;
                try {
                    String ip = objectData.getString("IP");
                    port = objectData.getInt("TCP");

                    connect(ip, port);
                    mHandler.postDelayed(runnable, 2000);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else if (msg.what == 1) {
                send("{\"lock\":\"open\"}");
            }
        }
    };

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 1;
            mHandler.sendMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scan_btn = findViewById(R.id.scan_btn);
        listText = findViewById(R.id.textView);
        phoneText = findViewById(R.id.phone);
        udpBuild = UDPBuild.getUdpBuild();
        udpBuild.setContext(MainActivity.this);
        mExecutorService = Executors.newCachedThreadPool();
        udpBuild.setUdpReceiveCallback(new UDPBuild.OnUDPReceiveCallbackBlock() {
            @Override
            public void OnParserComplete(DatagramPacket data) {
                String strReceive = new String(data.getData(), 0, data.getLength());
                Log.i("TAG", strReceive);
                try {
                    JSONObject object = new JSONObject(strReceive);
                    JSONObject objectData = object.getJSONObject("smartlock");
                    if (objectData.getString("MAC").equals(scanresult)) {
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = objectData;
                        mHandler.sendMessage(msg);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.i("TAG", "json 格式错误");
                }
            }
        });
        scan_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isPhone = false;
                String tellNUmber = getMyTellPhoneNumber();
                for (String tell:Config.PHONE_LIST){
                    if (tell.equals(tellNUmber)){
                        //打开扫描界面扫描条形码或二维码
                        isPhone = true;
                        Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
                        startActivityForResult(openCameraIntent, 0);
                        break;
                    }
                }
                if (!isPhone){
                    showTwo("手机号不匹配！");
                }

            }
        });
        listText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ListActivity.class);
                startActivity(intent);
            }
        });

        String phone = getMyTellPhoneNumber();
        phoneText.setText("当前手机号："+phone);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            Log.i("TAG", scanResult);
            //udpBuild.send(Config.UDP_SEND_COMMOND);
            scanresult = scanResult;
            udpBuild.sendMessage(Config.UDP_SEND_COMMOND);
        }
    }

    private class connectService implements Runnable {

        public String IP;
        public int port;

        connectService(String Ip, int port) {
            this.IP = Ip;
            this.port = port;
        }

        @Override
        public void run() {//可以考虑在此处添加一个while循环，结合下面的catch语句，实现Socket对象获取失败后的超时重连，直到成功建立Socket连接
            try {
                Socket socket = new Socket(this.IP, this.port);      //步骤一
                socket.setSoTimeout(60000);
                printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(   //步骤二
                        socket.getOutputStream(), "UTF-8")), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                // in = socket.getInputStream();
                receiveMsg();
            } catch (Exception e) {
                Log.e("TAG", ("connectService:" + e.getMessage()));   //如果Socket对象获取失败，即连接建立失败，会走到这段逻辑
            }
        }
    }

    public void connect(String ip, int port) {
        mExecutorService.execute(new connectService(ip, port));  //在一个新的线程中请求 Socket 连接
    }

    public void send(String message) {
        mExecutorService.execute(new sendService(message));
    }

    public void disconnect() {
        mExecutorService.execute(new sendService("0"));
    }

    private class sendService implements Runnable {
        private String msg;

        sendService(String msg) {
            this.msg = msg;
        }

        @Override
        public void run() {
            printWriter.println(this.msg);
        }
    }

    private void receiveMsg() {
        try {
            while (true) {                                      //步骤三
                if ((receiveMsg = in.readLine()) != null) {
                    Log.d("TAG", "receiveMsg:" + receiveMsg);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //  mTextView.setText(receiveMsg + "\n\n" + mTextView.getText());
                            try {
                                Log.i("TAG", "TCP receive: " + receiveMsg);
                                JSONObject object = new JSONObject(receiveMsg);
                                if (object.getString("lock").equals("open")) {
                                    showTwo("开锁成功!");
                                    Toast.makeText(MainActivity.this, "lock is open", Toast.LENGTH_LONG).show();
                                    // disconnect();
                                } else {
                                    Toast.makeText(MainActivity.this, "lock is close", Toast.LENGTH_LONG).show();
                                    //disconnect();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                //Thread.sleep(200);
            }
        } catch (IOException e) {
            // Log.e(TAG, "receiveMsg: ");
            e.printStackTrace();
        }
    }

    private String getMyTellPhoneNumber() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                RequestPermission(MainActivity.this,Manifest.permission.READ_PHONE_STATE,1);
            }
        }
        String deviceid = tm.getDeviceId();

        String tel = tm.getLine1Number();//手机号码
        Log.i("TAG",tel);
        return tel;
    }
    public void RequestPermission(Activity thisActivity, String Permission, int Code) {
        if (ContextCompat.checkSelfPermission(thisActivity,
                Permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Permission)) {
            } else {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Permission},
                        Code);
            }
        }
    }
    private void showTwo(String message) {

        builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage(message).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //ToDo: 你想做的事情
                        Toast.makeText(MainActivity.this, "确定按钮", Toast.LENGTH_LONG).show();
                    }
                });
        builder.create().show();
    }

}
